%% 自动连接SVG模型中的各个子系统
function connect_svg_subsystems(model_name)
    % 默认模型名
    if nargin < 1
        model_name = 'SVG_Star_10kV_Complete';
    end
    
    % 确保模型已打开
    if ~bdIsLoaded(model_name)
        open_system(model_name);
    end
    
    fprintf('开始连接子系统...\n');
    
    try
        %% 1. 电网连接
        % 获取端口句柄而不是使用端口名称
        % 强电网 -> 强电网阻抗
        strong_grid_ports = get_param([model_name '/Strong_Grid'], 'PortHandles');
        strong_grid_z_ports = get_param([model_name '/Strong_Grid_Z'], 'PortHandles');
        
        if ~isempty(strong_grid_ports.RConn) && ~isempty(strong_grid_z_ports.LConn)
            add_line(model_name, strong_grid_ports.RConn(1), strong_grid_z_ports.LConn(1), 'autorouting', 'on');
        end
        
        % 弱电网 -> 弱电网阻抗
        weak_grid_ports = get_param([model_name '/Weak_Grid_PV'], 'PortHandles');
        weak_grid_z_ports = get_param([model_name '/Weak_Grid_Z'], 'PortHandles');
        
        if ~isempty(weak_grid_ports.RConn) && ~isempty(weak_grid_z_ports.LConn)
            add_line(model_name, weak_grid_ports.RConn(1), weak_grid_z_ports.LConn(1), 'autorouting', 'on');
        end
        
        % 检查是否有Grid_Selector（可能还未创建）
        if exist_block(model_name, 'Grid_Selector')
            grid_sel_ports = get_param([model_name '/Grid_Selector'], 'PortHandles');
            
            % 强电网阻抗 -> 电网切换开关
            if ~isempty(strong_grid_z_ports.RConn) && ~isempty(grid_sel_ports.LConn) && length(grid_sel_ports.LConn) >= 1
                add_line(model_name, strong_grid_z_ports.RConn(1), grid_sel_ports.LConn(1), 'autorouting', 'on');
            end
            
            % 弱电网阻抗 -> 电网切换开关
            if ~isempty(weak_grid_z_ports.RConn) && ~isempty(grid_sel_ports.LConn) && length(grid_sel_ports.LConn) >= 2
                add_line(model_name, weak_grid_z_ports.RConn(1), grid_sel_ports.LConn(2), 'autorouting', 'on');
            end
            
            % 电网切换开关 -> SVG
            svg_ports = get_param([model_name '/Star_SVG'], 'PortHandles');
            if ~isempty(grid_sel_ports.RConn) && ~isempty(svg_ports.LConn)
                add_line(model_name, grid_sel_ports.RConn(1), svg_ports.LConn(1), 'autorouting', 'on');
            end
        else
            % 如果没有切换开关，直接连接强电网到SVG
            svg_ports = get_param([model_name '/Star_SVG'], 'PortHandles');
            if ~isempty(strong_grid_z_ports.RConn) && ~isempty(svg_ports.LConn)
                add_line(model_name, strong_grid_z_ports.RConn(1), svg_ports.LConn(1), 'autorouting', 'on');
            end
        end
        
        fprintf('  电网连接完成\n');
        
        %% 2. SVG到负载连接
        % SVG输出 -> 负载
        svg_ports = get_param([model_name '/Star_SVG'], 'PortHandles');
        load_ports = get_param([model_name '/Mixed_Load'], 'PortHandles');
        
        if ~isempty(svg_ports.RConn) && ~isempty(load_ports.LConn)
            add_line(model_name, svg_ports.RConn(1), load_ports.LConn(1), 'autorouting', 'on');
        end
        
        fprintf('  SVG到负载连接完成\n');
        
        %% 3. 测量连接
        % 在电网和SVG之间添加测量点
        % 这需要先断开原有连接，插入测量模块
        
        % 删除原有的Grid到SVG的连接
        delete_line(model_name, 'Grid_Selector/1', 'Star_SVG/1');
        
        % Grid -> Grid测量
        add_line(model_name, 'Grid_Selector/1', 'Measurements/Grid_VI/1', 'autorouting', 'on');
        
        % Grid测量 -> SVG
        add_line(model_name, 'Measurements/Grid_VI/2', 'Star_SVG/1', 'autorouting', 'on');
        
        % 在SVG和负载之间添加测量
        delete_line(model_name, 'Star_SVG/1', 'Mixed_Load/1');
        
        % SVG -> SVG测量
        add_line(model_name, 'Star_SVG/1', 'Measurements/SVG_VI/1', 'autorouting', 'on');
        
        % SVG测量 -> 负载测量
        add_line(model_name, 'Measurements/SVG_VI/2', 'Measurements/Load_VI/1', 'autorouting', 'on');
        
        % 负载测量 -> 负载
        add_line(model_name, 'Measurements/Load_VI/2', 'Mixed_Load/1', 'autorouting', 'on');
        
        fprintf('  测量系统连接完成\n');
        
        %% 4. 控制信号连接
        % 测量信号到控制系统
        % Grid_VI的电压测量 -> SCR检测
        add_line(model_name, 'Measurements/Grid_VI/3', 'Control_System/1', 'autorouting', 'on');
        
        % Grid_VI的电流测量 -> SCR检测
        add_line(model_name, 'Measurements/Grid_VI/4', 'Control_System/2', 'autorouting', 'on');
        
        % SVG_VI的测量 -> 控制系统
        add_line(model_name, 'Measurements/SVG_VI/3', 'Control_System/3', 'autorouting', 'on');
        add_line(model_name, 'Measurements/SVG_VI/4', 'Control_System/4', 'autorouting', 'on');
        
        % 控制系统PWM输出 -> SVG
        add_line(model_name, 'Control_System/1', 'Star_SVG/2', 'autorouting', 'on');
        
        fprintf('  控制信号连接完成\n');
        
        %% 5. 储能系统连接
        % 储能系统DC/DC输出连接到SVG各H桥
        % 这需要在SVG子系统内部进行连接
        connect_storage_to_svg(model_name);
        
        fprintf('  储能系统连接完成\n');
        
        %% 6. 显示系统连接
        % 连接各测量信号到示波器
        connect_to_scopes(model_name);
        
        fprintf('  显示系统连接完成\n');
        
        %% 7. 设置电网切换开关的控制信号
        % 添加一个时间控制信号在t=0.5s切换
        add_block('simulink/Sources/Step', [model_name '/Grid_Switch_Control']);
        set_param([model_name '/Grid_Switch_Control'], 'Position', [200 300 250 330]);
        set_param([model_name '/Grid_Switch_Control'], 'Time', '0.5');
        set_param([model_name '/Grid_Switch_Control'], 'Before', '0');
        set_param([model_name '/Grid_Switch_Control'], 'After', '1');
        
        % 连接到电网切换开关控制端
        add_line(model_name, 'Grid_Switch_Control/1', 'Grid_Selector/3', 'autorouting', 'on');
        
        fprintf('  电网切换控制连接完成\n');
        
    catch ME
        fprintf('连接过程中出现错误: %s\n', ME.message);
        fprintf('请检查模型结构并手动完成剩余连接。\n');
    end
    
    % 自动布局
    Simulink.BlockDiagram.arrangeSystem(model_name);
    
    fprintf('所有子系统连接完成！\n');
    fprintf('提示：某些内部连接可能需要手动调整。\n');
end

%% 子函数：连接储能系统到SVG
function connect_storage_to_svg(model_name)
    % 这个函数需要进入SVG和储能子系统内部进行连接
    % 由于结构复杂，这里提供基本框架
    
    svg_subsys = [model_name '/Star_SVG'];
    storage_subsys = [model_name '/Energy_Storage'];
    
    % 获取各相的H桥和对应的储能单元
    phases = {'A', 'B', 'C'};
    N_bridge = 11;
    
    for i = 1:length(phases)
        for j = 1:N_bridge
            % 储能DC/DC输出端口
            storage_port = sprintf('%s/DCDC_%s%d/1', storage_subsys, phases{i}, j);
            
            % SVG H桥DC端口
            svg_dc_port = sprintf('%s/Phase_%s/HBridge_%d/DC+', svg_subsys, phases{i}, j);
            
            % 尝试连接（可能需要通过中间端口）
            try
                add_line(model_name, storage_port, svg_dc_port, 'autorouting', 'on');
            catch
                % 如果直接连接失败，可能需要添加端口或调整路径
                fprintf('  警告：无法自动连接储能%s%d到SVG，请手动连接\n', phases{i}, j);
            end
        end
    end
end

%% 子函数：连接测量信号到示波器
function connect_to_scopes(model_name)
    meas_subsys = [model_name '/Measurements'];
    disp_subsys = [model_name '/Display_System'];
    
    % 定义连接映射
    connections = {
        'Grid_VI/3', 'Grid_Voltage_Scope/1';    % 电网电压
        'Grid_VI/4', 'Grid_Current_Scope/1';    % 电网电流
        'SVG_VI/3', 'SVG_Voltage_Scope/1';      % SVG电压
        'SVG_VI/4', 'SVG_Current_Scope/1';      % SVG电流
        'Power_Calc/1', 'Power_PQ_Scope/1';     % 有功无功功率
        'THD_Grid/1', 'THD_Scope/1';            % THD
    };
    
    for i = 1:size(connections, 1)
        src = [meas_subsys '/' connections{i, 1}];
        dst = [disp_subsys '/' connections{i, 2}];
        
        try
            add_line(model_name, src, dst, 'autorouting', 'on');
        catch
            fprintf('  警告：无法连接 %s 到 %s\n', src, dst);
        end
    end
    
    % 连接控制系统的输出到显示
    try
        add_line(model_name, 'Control_System/SCR_Detection/1', ...
                 [disp_subsys '/SCR_Scope/1'], 'autorouting', 'on');
    catch
        fprintf('  警告：无法连接SCR检测输出到显示\n');
    end
end